<?php

namespace App\Http\Controllers;

use App\Http\Requests\DepartmentStoreRequest;
use App\Models\Department;
use App\Models\UserDepartment;
use Illuminate\Http\Request;

class DepartmentController extends Controller
{
    /**
     * 部门列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request): \Illuminate\Http\JsonResponse
    {
        $departments = new Department();
        $departments  = $departments->index($request);
        return response()->json(['data' => $departments]);
    }

    /**
     * 新增部门
     * @param DepartmentStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(DepartmentStoreRequest $request): \Illuminate\Http\JsonResponse
    {
        $data = $request->safe()->only(['name', 'description', 'parent_id']);
        Department::create($data);
        return response()->json(['message' => '新增部门成功']);
    }

    /**
     * 查看部门详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id): \Illuminate\Http\JsonResponse
    {
        $department = Department::find($id);
        return response()->json(['data' => $department]);
    }

    /**
     * 更新部门
     * @param DepartmentStoreRequest $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(DepartmentStoreRequest $request, $id): \Illuminate\Http\JsonResponse
    {
        $department = Department::find($id);
        $department->update($request->only(['name', 'description', 'parent_id']));
        return response()->json(['message' => '更新部门成功']);
    }

    /**
     * 删除部门
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id): \Illuminate\Http\JsonResponse
    {
        Department::destroy($id);
        // 判断是否有子部门，如果有子部门，则提示需要先删除子部门
        $childDepartment = Department::where('parent_id', $id)->first();
        if ($childDepartment) {
            return response()->json(['message' => '请先删除子部门'], 400);
        }
        // 判断是否有员工，如果有员工，则提示需要先删除员工
        $staff = UserDepartment::where('department_id', $id)->first();
        if ($staff) {
            return response()->json(['message' => '请先删除员工'], 400);
        }
        return response()->json(['message' => '删除部门成功']);
    }
}

